package jwt

import (
	"api/global"
	"errors"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type TokenClaims struct {
	Id       string `json:"id"`
	Username string `json:"username"`
	Role     int    `json:"role"`
	jwt.StandardClaims
}

func GenToken(id, username string, role int) (accessToken, refreshToken string, err error) {
	c := TokenClaims{
		id,       // customize column
		username, // customize column
		role,     // customize column
		jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + global.AppConfig.Jwt.ExpiresAt,
			Issuer:    "issuer",
		},
	}
	accessToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, c).SignedString([]byte(global.AppConfig.Jwt.Secret))
	if err != nil {
		return
	}

	rc := jwt.StandardClaims{
		ExpiresAt: time.Now().Unix() + 60*60*24*7,
		Issuer:    "issuer",
	}
	refreshToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, rc).SignedString([]byte(global.AppConfig.Jwt.Secret))
	if err != nil {
		return
	}
	return
}

func ParseToken(tokenString string) (*TokenClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(global.AppConfig.Jwt.Secret), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*TokenClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}

func RefreshToken(accessToken, refreshToken string) (newAccessToken, newRefreshToken string, err error) {
	_, err = jwt.Parse(refreshToken, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(global.AppConfig.Jwt.Secret), nil
	})
	if err != nil {
		return
	}

	var c TokenClaims
	_, err = jwt.ParseWithClaims(accessToken, &c, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(global.AppConfig.Jwt.Secret), nil
	})

	v, _ := err.(*jwt.ValidationError)
	if v.Errors == jwt.ValidationErrorExpired {
		return GenToken(c.Id, c.Username, c.Role)
	}
	return
}
